package web

import (
	"commerce/common"
	"commerce/data"
	"commerce/model"
	"commerce/req"
	"commerce/vo"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
)

/* 此文件是 app 地址 请求 */

func ListAddr(w http.ResponseWriter, r *http.Request) {

	member := extractUserFromContext(r)
	if member == nil || member.Mid <= 0 {
		common.DisplayTokenErr(w, http.StatusUnauthorized)
		return
	}
	addrList, err := data.ListMemberReceiveAddr(member.Mid)
	if err != nil {
		common.Error.Printf("ListAddr err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	var res []vo.CheckedAddrVo
	for _, addr := range addrList {
		res = append(res, vo.CheckedAddrVo{Id: addr.Id, Name: addr.Name, TelNumber: addr.Phone,
			IsDefault: addr.DefaultStatus, DetailInfo: addr.DetailAddr,
			FullRegion: fmt.Sprintf("%s/%s/%s", addr.Province, addr.City, addr.Region)})
	}
	j, _ := json.Marshal(vo.Ok(res))
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}

func AddrDetail(w http.ResponseWriter, r *http.Request) {

	member := extractUserFromContext(r)
	if member == nil || member.Mid <= 0 {
		common.DisplayTokenErr(w, http.StatusUnauthorized)
		return
	}
	addressId, _ := strconv.Atoi(r.PostFormValue("id"))
	addr, err := data.GetMemberReceiveAddrById(addressId)
	if err != nil {
		common.Error.Printf("AddrDetail err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	res := vo.CheckedAddrVo{Id: addr.Id, Name: addr.Name, TelNumber: addr.Phone,
		IsDefault: addr.DefaultStatus, DetailInfo: addr.DetailAddr, ProvinceId: addr.ProvinceId, CityId: addr.CityId, RegionId: addr.RegionId,
		ProvinceName: addr.Province, CityName: addr.City, RegionName: addr.Region, FullRegion: fmt.Sprintf("%s/%s/%s", addr.Province, addr.City, addr.Region)}

	j, _ := json.Marshal(vo.Ok(res))
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}

func RegionList(w http.ResponseWriter, r *http.Request) {

	member := extractUserFromContext(r)
	if member == nil || member.Mid <= 0 {
		common.DisplayTokenErr(w, http.StatusUnauthorized)
		return
	}
	// 1 表示顶级类别
	parentAddrId, _ := strconv.Atoi(r.PostFormValue("parentId"))
	// 1-省，2-市，3-区
	regionType, _ := strconv.Atoi(r.PostFormValue("regionType"))

	if parentAddrId <= 0 || regionType != 1 && regionType != 2 && regionType != 3 {
		common.Error.Println("RegionList err:参数非法！")
		j, _ := json.Marshal(vo.Err("参数非法！"))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusBadRequest)
		w.Write(j)
		return
	}
	var res []vo.RegionVo
	if parentAddrId == 1 || regionType == 1 {
		provinces, err := data.ListProvince()
		if err != nil {
			common.Error.Printf("2.RegionList err:%v", err)
			j, _ := json.Marshal(vo.Err(err.Error()))
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusBadRequest)
			w.Write(j)
			return
		}
		for _, p := range provinces {
			res = append(res, vo.RegionVo{Id: p.ProvinceId, Name: p.Province, ParentId: 1, Type: 1})
		}
	} else {
		switch regionType {
		case 2:
			cities, err := data.ListCity(parentAddrId)
			if err != nil {
				common.Error.Printf("3.RegionList err:%v", err)
				j, _ := json.Marshal(vo.Err(err.Error()))
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusBadRequest)
				w.Write(j)
				return
			}
			for _, c := range cities {
				res = append(res, vo.RegionVo{Id: c.CityId, Name: c.City, ParentId: c.ProvinceId, Type: 2})
			}
		case 3:
			regions, err := data.ListRegion(parentAddrId)
			if err != nil {
				common.Error.Printf("4.RegionList err:%v", err)
				j, _ := json.Marshal(vo.Err(err.Error()))
				w.Header().Set("Content-Type", "application/json")
				w.WriteHeader(http.StatusBadRequest)
				w.Write(j)
				return
			}
			for _, r := range regions {
				res = append(res, vo.RegionVo{Id: r.AreaId, Name: r.Area, ParentId: r.CityId, Type: 3})
			}
		}
	}
	j, _ := json.Marshal(vo.Ok(res))
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}

func SaveAddr(w http.ResponseWriter, r *http.Request) {

	member := extractUserFromContext(r)
	if member == nil || member.Mid <= 0 {
		common.DisplayTokenErr(w, http.StatusUnauthorized)
		return
	}
	var rr req.SaveAddrReq
	err := json.NewDecoder(r.Body).Decode(&rr)
	if err != nil {
		common.Error.Printf("SaveAddr err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	var defaultStatus int8 = 1
	if !rr.IsDefault {
		defaultStatus = 0
	}
	addr := model.MemberReceiveAddr{MemberId: member.Mid, Name: rr.Name, Phone: rr.TelNumber,
		ProvinceId: rr.ProvinceId, Province: rr.Province, CityId: rr.CityId, City: rr.City, RegionId: rr.RegionId,
		Region: rr.Region, DetailAddr: rr.DetailInfo, DefaultStatus: defaultStatus}
	// 修改操作
	if rr.Id > 0 {
		addr.Id = rr.Id
		_, err = data.UpdateMemberReceiveAddr(addr)
	} else {
		// 新增操作
		_, err = data.AddMemberReceiveAddr(addr)
	}

	if err != nil {
		common.Error.Printf("2.SaveAddr err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	j, _ := json.Marshal(vo.Ok(nil))
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}

func DeleteAddr(w http.ResponseWriter, r *http.Request) {

	member := extractUserFromContext(r)
	if member == nil || member.Mid <= 0 {
		common.DisplayTokenErr(w, http.StatusUnauthorized)
		return
	}
	var deleteReq req.DeleteAddrReq
	err := json.NewDecoder(r.Body).Decode(&deleteReq)
	if err != nil {
		common.Error.Printf("DeleteAddr err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	err = data.DeleteAddr(deleteReq.Id, member.Mid)
	if err != nil {
		common.Error.Printf("2.DeleteAddr err:%v", err)
		j, _ := json.Marshal(vo.Err(err.Error()))
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write(j)
		return
	}
	j, _ := json.Marshal(vo.Ok(nil))
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(j)
}
